package com.headFirstModel.commandPattern;

import com.headFirstModel.commandPattern.command.Command;
import com.headFirstModel.commandPattern.command.NoCommand;

import java.util.Stack;

/**
 * 遥控器:控制一组开关
 *      有7组插槽，每个插槽2个开关控制命令
 */
public class RomoteControl {
    Command[] onCommands;
    Command[] offCommands;

    Stack<Command> undoCommands;

    public RomoteControl(){
        onCommands=new Command[7];
        offCommands=new Command[7];
        Command noCommand=new NoCommand();
        for (int i=0;i<7;i++){
            onCommands[i]=noCommand;
            offCommands[i]=noCommand;
        }
        undoCommands=new Stack<Command>();
    }

    /**
     * 设置指定插槽命令
     */
    public void setCommand(int slot,Command onCommand,Command offCommand){
        if(slot<0||slot>6){
            System.out.println("找不到该插槽......");
        }
        this.onCommands[slot]=onCommand;
        this.offCommands[slot]=offCommand;
    }

    /**
     * 当按下 开 的开关执行命令
     * @param slot
     */
    public void onButtonWasPushed(int slot){
        onCommands[slot].execute();
        undoCommands.push(onCommands[slot]);
    }

    /**
     * 当按下 关 的开关执行命令
     * @param slot
     */
    public void offButtonWasPushed(int slot){
        offCommands[slot].execute();
        undoCommands.push(offCommands[slot]);
    }

    /***
     * 撤销操作
     */
    public void undoButtonWasPushed(){
        if (undoCommands.empty()) {
            System.out.println("已经撤销到最后一步:无法在撤销...");
            return;
        }
        Command command=undoCommands.pop();
        System.out.print("撤销:");
        command.undo();

    }

    public String toString(){
        StringBuffer sb=new StringBuffer();
        sb.append("\n------Remote Control------\n");
        for (int i=0;i<onCommands.length;i++){
            sb.append("slot "+i+"] "+onCommands[i].getClass().getName()+
            "  "+offCommands[i].getClass().getName()+"\n");
        }
        return  sb.toString();
    }

}
